package com.fancy.learncenter.ui.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CartoonQuestionBankBean;
import com.fancy.learncenter.bean.CartoonWorkItemBean;
import com.fancy.learncenter.bean.QuestionVOsBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.common.JumpIntentKey;
import com.fancy.learncenter.common.LoginUserSharePrefernce;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.CartoonQuestionTypeActivity;
import com.fancy.learncenter.ui.activity.CartoonStaticsActivity;
import com.fancy.learncenter.ui.adapter.base.CommonRecycleViewAdapter;
import com.fancy.learncenter.ui.adapter.base.CustomViewHold;
import com.fancy.learncenter.utils.FileUtils;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.Utils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.fanrunqi.waveprogress.WaveProgressView;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * Created by shiweiwei on 2017/12/7.
 */

public class CurrentWorkAdapter extends CommonRecycleViewAdapter<CartoonWorkItemBean> {
    Activity context;
    private int progress;
    private static final int one = 0X0001;
    Gson gson = new Gson();
    ArrayList<QuestionVOsBean> list = new ArrayList<>();

    public CurrentWorkAdapter(Activity mContext, List<CartoonWorkItemBean> itemDatas) {
        super(mContext, R.layout.current_work_item, itemDatas);
        this.context = mContext;
    }

    @Override
    public void bindView(CustomViewHold customViewHold, final CartoonWorkItemBean item, final int position) {

        final ImageView work_status = customViewHold.getView(R.id.work_status);
        final ImageView download_image = customViewHold.getView(R.id.download_image);
        final ImageView is_new = customViewHold.getView(R.id.is_new);
        final WaveProgressView waveProgressbar = customViewHold.getView(R.id.waveProgressbar);
        TextView teach_book_name = customViewHold.getView(R.id.teach_book_name);
        TextView end_time = customViewHold.getView(R.id.end_time);
        TextView unit_name = customViewHold.getView(R.id.unit_name);
        teach_book_name.setText(item.getLessonName());
        end_time.setText("截止日期: " + item.getEndTime());

        if (!TextUtils.isEmpty(item.getUnitName())) {
            unit_name.setText(item.getUnitName());
        }
        download_image.setVisibility(View.GONE);
        waveProgressbar.setWaveColor("#5b9ef4");
        waveProgressbar.setmWaveSpeed(30);
        isNeedDownload(item, download_image, is_new, work_status);


        if (item.getHomeworkState() == 0) {
            work_status.setImageResource(R.mipmap.do_work);
        } else {
            work_status.setImageResource(R.mipmap.redo_work);
        }
//        final Handler handler = new Handler(){
//
//            @Override
//            public void handleMessage(Message msg) {
//                super.handleMessage(msg);
//                progress++;
//                switch (msg.what){
//                    case one:
//                        if (progress<= 100){
//                            waveProgressbar.setCurrent(progress,"");
//                            sendEmptyMessageDelayed(one,1000);
//                        }else {
//                            waveProgressbar.setVisibility(View.GONE);
//                            work_status.setVisibility(View.VISIBLE);
//                        }
//                        break;
//                }
//            }
//        };


        download_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                download_image.setVisibility(View.GONE);
                work_status.setVisibility(View.GONE);
//                waveProgressbar.setVisibility(View.VISIBLE);
                progress = 0;

                String fileName = Constant.CARTOON_QUESTION_BANK + String.valueOf(LoginUserSharePrefernce.getCustomId() + "_" + item.getHomePackageId()) + ".td";
                downloadWork(fileName, item.getStudentHomeworkId(), item.getReleaseTime());

                work_status.setVisibility(View.VISIBLE);

            }
        });
        work_status.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(mContext, CartoonStaticsActivity.class);
                intent.putExtra(JumpIntentKey.LESSON_NAME, item.getLessonName());
                intent.putExtra("releaseTime", item.getReleaseTime());
                intent.putExtra(JumpIntentKey.STUDENTHOMEWORKID, item.getStudentHomeworkId());
                intent.putExtra(JumpIntentKey.QUESTION_ENTER, JumpIntentKey.QUESTION_ENTER_TYPE.DO_WORK);
                intent.putExtra(JumpIntentKey.UNIT_NAME, String.valueOf(item.getUnitName()));
                intent.putExtra(JumpIntentKey.STUDENTHOMEWORKID, String.valueOf(item.getStudentHomeworkId()));
                intent.putExtra(JumpIntentKey.HOMEWORK_PACKAGE_ID, String.valueOf(item.getHomePackageId()));
                mContext.startActivity(intent);

            }
        });
    }

    private void isNeedDownload(CartoonWorkItemBean item, ImageView download_image, ImageView is_new, ImageView work_status) {
        FileUtils.createDir(Constant.CARTOON_QUESTION_BANK);

        String fileName = String.valueOf(LoginUserSharePrefernce.getCustomId() + "_" + item.getHomePackageId()) + ".td";

        if (!FileUtils.checKFileExists(Constant.CARTOON_QUESTION_BANK + fileName)) {
            work_status.setVisibility(View.GONE);
            is_new.setVisibility(View.GONE);
            download_image.setVisibility(View.VISIBLE);
            download_image.setImageResource(R.mipmap.cartoon_download);
        } else {

            String readResultStr = FileUtils.readFromSD(Constant.CARTOON_QUESTION_BANK + fileName);
            Gson gson = new Gson();
            CartoonQuestionBankBean questionBankBean1 = gson.fromJson(readResultStr, CartoonQuestionBankBean.class);


            if (item.getReleaseTime().equals(questionBankBean1.getReleaseTime())) {
                download_image.setVisibility(View.GONE);
                work_status.setVisibility(View.VISIBLE);
                contiuneOrStart(item, work_status);
                is_new.setVisibility(View.GONE);
            } else {
                work_status.setVisibility(View.GONE);
                is_new.setVisibility(View.VISIBLE);
                download_image.setVisibility(View.VISIBLE);
                download_image.setImageResource(R.mipmap.cartoon_download);
            }

        }

    }


    private void contiuneOrStart(CartoonWorkItemBean item, ImageView download_image) {

        switch (item.getState()) {

            case 0:
                download_image.setImageResource(R.mipmap.do_work);
                break;
            case 1:
                download_image.setImageResource(R.mipmap.cartoon_continue_work);
                break;
        }

    }


    /**
     * 下载作业包
     *
     * @param fileName
     * @param homeworkId
     */
    private void downloadWork(final String fileName, long homeworkId, final String releaseTime) {


        Map<String, Object> map = new HashMap<>();
        map.put("studentHomeworkId", String.valueOf(homeworkId));
        HttpMehtod.getInstance().cartoonDownloadHomeWorkById(map, new CustomNetSubscriber(context) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonQuestionBankBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonQuestionBankBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(context, baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonQuestionBankBean>() {
                    @Override
                    public void success(CartoonQuestionBankBean dataBean) {

                        dataBean.setReleaseTime(releaseTime);

                        Gson gson = new Gson();

                        String str = gson.toJson(dataBean);

                        FileUtils.creatFile(fileName);

                        FileUtils.saveStringToFile(fileName, str);

                        notifyDataSetChanged();
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });
    }


}
